import { Switch } from "antd";
import { ReactNode, useState } from "react";

interface TableSwitchProps<D extends Record<string, any>> {
    getList: () => Promise<unknown>;
    updateRecord: (record: D) => Promise<unknown>;
    record: D;
    dataIndex: keyof D;
    checkedChildren?: ReactNode;
    unCheckedChildren?: ReactNode;
}

const TableSwitch = <D extends Record<string, any>>(props: TableSwitchProps<D>) => {
    const { record, getList, dataIndex, updateRecord, checkedChildren, unCheckedChildren } = props;
    const [loading, setLoading] = useState(false);
    return (
        <Switch
            checkedChildren={checkedChildren || "启用"}
            unCheckedChildren={unCheckedChildren || "禁用"}
            value={record[dataIndex]}
            loading={loading}
            onChange={async val => {
                setLoading(true);
                try {
                    await updateRecord({ ...record, [dataIndex]: val });
                    getList?.();
                } finally {
                    setLoading(false);
                }
            }}
        />
    );
};

export default TableSwitch;
